class SessionController < ApplicationController
  before_filter :already_logged_in?,  :only => [:new, :create]
  
  def new
    session[:return_to] = request.referer
    redirect_to user_galleries_url(current_user) unless current_user.galleries.empty? if logged_in?
  end

  def create
    self.current_user = User.authenticate(params[:login], params[:password])
    if logged_in?
      if params[:remember_me] == "1"
        current_user.remember_me unless current_user.remember_token?
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      flash[:update] = "Hello " + current_user.login.to_s + ". Thanks for logging in."
      @user = current_user
      @user.galleries.empty? ? redirect_back_or_default('/') : (redirect_to user_galleries_url(@user))
    else
      flash[:error] = "Oops, that didn't work. Try again..."
      render :action => 'new'
    end
  end

  def destroy
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "See ya later!"
    redirect_back_or_default('/')
  end

protected
  def already_logged_in?
    (current_user.galleries.empty? ? redirect_back_or_default('/') : (redirect_to user_galleries_url(current_user))) if logged_in? && !current_user.is_admin?
  end
end
